import { ref } from "vue"
import { getToken } from "@/utils/index"
const base_url = 'https://raingjy.microport.com/qjdapi' //https://raingjy.microport.com/qjdapi    http://10.100.2.94:9011
const timeout = 5000

let isReturnSuccess = ref<boolean>(false)

const request = (params : any) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': getToken(),
		...params.header
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			timeout,
			success(response) {
				const res = response.data as any
				if (res.code == 200) {
					resolve(res);
				} else {
					switch (res.code) {
						case 401:
							uni.removeStorageSync('wxToken')
							const pages = getCurrentPages();
							const currentPage = pages[pages.length - 1];
							let isLoginPage = currentPage.route == 'pages/login/index'
							if(!isLoginPage && !isReturnSuccess.value){
								uni.showToast({
									title: "请重新登录",
									icon: 'none',
									success() {
										setTimeout(() => {
											uni.reLaunch({
												url: "/pages/login/index",
												success() {
													isReturnSuccess.value = false
												}
											})
										}, 1500);
									},
								});
								isReturnSuccess.value = true
							}
							
							break;
						case 500:
							uni.showToast({
								icon: 'none',
								title: res.msg || '接口500，无报错信息',
								duration: 2000,
							})
							break;
						case 404:
							uni.showToast({
								icon: 'none',
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						case 403:
							uni.showToast({
								icon: 'none',
								title: res.msg,
								duration: 2000,
							})
							break;
						default:
							uni.showToast({
								icon: 'none',
								title: '请重试...',
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);
			},
			complete() {
			}
		});
	}).catch(() => {
	});
};

export default request;